// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

#ifndef APP_IMAGE_H_
#define APP_IMAGE_H_

#include <stdint.h>
#include <stddef.h>
#include "status/rot_status.h"
#include "flash/flash.h"
#include "crypto/rsa.h"
#include "crypto/hash.h"


/**
 * The length of the application image signature.
 */
#define	APP_IMAGE_SIG_LENGTH	256


int app_image_verification (struct flash *flash, uint32_t start_addr, struct hash_engine *hash,
	struct rsa_engine *rsa, const struct rsa_public_key *pub_key, uint8_t *hash_out,
	size_t hash_length);
int app_image_verification_with_header (struct flash *flash, uint32_t start_addr,
	size_t header_length, struct hash_engine *hash, struct rsa_engine *rsa,
	const struct rsa_public_key *pub_key, uint8_t *hash_out, size_t hash_length);

int app_image_load (struct flash *flash, uint32_t start_addr, uint8_t *load_addr, size_t max_length,
	size_t *load_length);
int app_image_load_and_verify (struct flash *flash, uint32_t start_addr, uint8_t *load_addr,
	size_t max_length, struct hash_engine *hash, struct rsa_engine *rsa,
	const struct rsa_public_key *pub_key, uint8_t *hash_out, size_t hash_length,
	size_t *load_length);
int app_image_load_and_verify_with_header (struct flash *flash, uint32_t start_addr,
	size_t header_length, uint8_t *load_addr, size_t max_length, struct hash_engine *hash,
	struct rsa_engine *rsa, const struct rsa_public_key *pub_key, uint8_t *hash_out,
	size_t hash_length, size_t *load_length);

int app_image_get_signature (struct flash *flash, uint32_t start_addr, uint8_t *sig_out,
	size_t sig_length);
int app_image_get_hash (struct flash *flash, uint32_t start_addr, struct hash_engine *hash,
	uint8_t *hash_out, size_t hash_length);
int app_image_get_hash_with_header (struct flash *flash, uint32_t start_addr, size_t header_length,
	struct hash_engine *hash, uint8_t *hash_out, size_t hash_length);

int app_image_get_data_addr (struct flash *flash, uint32_t start_addr, uint32_t *data_addr);
int app_image_get_length (struct flash *flash, uint32_t start_addr, uint32_t *img_length);
int app_image_get_image_end (struct flash *flash, uint32_t start_addr, uint32_t *end_addr);


#define	APP_IMAGE_ERROR(code)		ROT_ERROR (ROT_MODULE_APP_IMAGE, code)

/**
 * Error codes that can be generated by the application image utilities.
 */
enum {
	APP_IMAGE_INVALID_ARGUMENT = APP_IMAGE_ERROR (0x00),		/**< Input parameter is null or not valid. */
	APP_IMAGE_NO_MEMORY = APP_IMAGE_ERROR (0x01),				/**< Memory allocation failed. */
	APP_IMAGE_TOO_LARGE = APP_IMAGE_ERROR (0x02),				/**< There is not enough space available to load the image. */
	APP_IMAGE_HASH_BUFFER_TOO_SMALL = APP_IMAGE_ERROR (0x03),	/**< The buffer for the image hash is not large enough. */
	APP_IMAGE_SIG_BUFFER_TOO_SMALL = APP_IMAGE_ERROR (0x04),	/**< The buffer for the signature is not large enough. */
};


#endif /* APP_IMAGE_H_ */
